<?php

namespace app\admin\controller\system;

use app\admin\model\SystemGroupAdmin;
use app\admin\model\SystemGroupMenu;
use app\admin\service\MenuService;
use app\common\controller\AdminBase;
use app\common\controller\PCBase;
use think\App;
use think\exception\ValidateException;
use think\facade\Log;

/**
 * 角色组控制器
 */
class Role extends PCBase
{

    protected $model = null;
    protected $validate = null;
    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\SystemGroup();

    }


    /**
     * 列表
     */
    public function index()
    {
        $params      = $this->request->post();
        $name        = $params['name']??'';
        $id          = $params['id']??'';
        $status      = $params['status']??'';
        $limit       = $params['limit']??10;
        $where       = [];
        if($name){
            $where[] = ['name','=',trim($name)];
        }

        if($status!==''){
            $where[] = ['status','=',$status];
        }

        if($id){
            $where[] = ['id','=',trim($id)];
        }


        $list = $this->model
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $data = [
            'total' => $list->total(),
            'list'  => $list->items(),
        ];
        return $this->jsonMessage(200, true, '获取成功!', $data);
    }



    /**
     * 授权数据
     */

    public function authData()
    {
        $id = $this->request->post('id');
        if (!$id) {
            return $this->jsonMessage(201, false, 'id不能为空', null);
        }
        $menuService = new MenuService(0);
        $menuList = $menuService->getAuthMenuData($id);
        return $this->jsonMessage(200, true, '获取成功', $menuList);
    }


    /**
     * @return \think\response\Json|void
     * @desc  新增
     */
    public function add()
    {
        $post = $this->request->post();
        try {
            $this->validate && validate($this->validate)->check($post);
            $result = $this->model->save($post);
            if ($result) {
                return $this->jsonMessage(200, true, '添加成功',null);
            }
            return $this->jsonMessage(201, false, '添加失败',null);
        } catch (ValidateException $e) {
            return $this->jsonMessage(201, false, $e->getError(),null);
        } catch (\Exception $e) {
            return $this->jsonMessage(201, false, '添加失败',null);
        }

    }



    /**
     * 授权角色组数据
     */
    public function authGroup()
    {
        $id = $this->request->post('id');
        $menu_ids = $this->request->post('menu_ids');
        if (!$id || !$menu_ids) {
            return $this->jsonMessage(201, false, '参数不能为空', null);
        }
        $group = [];
        $menuArr = $menu_ids;
        foreach ($menuArr as $k => $v) {
            $row['group_id'] = $id;
            $row['menu_id'] = $v;
            $group[] = $row;
        }
        try {
            $group_menu_model = new SystemGroupMenu();
            $group_menu_model->where('group_id', $id)->delete();
            $group_menu_model->saveAll($group);
        } catch (\Exception $e) {
            Log::error("--group authGroup error:---" . $e);
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
        return $this->jsonMessage(200, true, '操作成功', null);
    }

    /**
     * 状态启用、禁用
     */
    public function status($id, $status)
    {
        if ($id == 1) {
            return $this->jsonMessage(201, false, '超级管理员不可以修改', null);
        }
        $row = $this->model->find($id);
        if (empty($row)) {
            return $this->jsonMessage(201, false, '数据不存在', null);
        }
        $msg = $status == 0 ? "禁用" : "启用";
        try {
            $row->status = $status;
            $row->save();
            return $this->jsonMessage(200, true, '操作成功!', null);
        } catch (\Exception $e) {
            return $this->jsonMessage(201, false, '操作失败!', null);
        }
    }

    /**
     * 数据删除
     */
    public function delete($id)
    {
        $ids = is_array($id) ? $id : explode(',', $id);
        $row = $this->model->where("id", "in", $ids)->select();
        if ($row->isEmpty()) {
            return $this->jsonMessage(201, false, '数据不存在', null);
        }
        $save = 1;
        if (in_array("1", $ids) || in_array(1, $ids)) {
            return $this->jsonMessage(201, false, '超级管理员不可以删除', null);
        }
        try {
            $count = SystemGroupAdmin::where('group_id', 'in', $ids)->count();
            if ($count > 0) {
                return $this->jsonMessage(201, false, '当前角色组下有管理员不能删除!', null);
            }
            $save = $row->delete();
        } catch (\Exception $e) {
            return $this->jsonMessage(201, false, '删除失败!', null);
        }
        if($save){
            return $this->jsonMessage(200, true, '删除成功!', null);
        }else{
            return $this->jsonMessage(201, false, '删除失败', null);
        }

    }

    /**
     * 下拉选择列表
     *
     */
    public function selectList()
    {
        try {
            $fields = input('fields');
            if (empty($fields)) {
                $fields = "id,name";
            }
            $data = $this->model
                ->field($fields)
                ->where('status', 1)
                ->limit(100)
                ->select();
            return $this->jsonMessage(200, true, '获取成功!', $data);
        } catch (\Exception $e) {
            Log::error("--------:" . $e);
            return $this->jsonMessage(201, false, '获取数据失败', null);
        }

    }


    /**
     * 查找
     */
    public function find($id)
    {
        $row = $this->model->find($id);
        if (empty($row)) {
            return $this->jsonMessage(201, false, '数据不存在', null);
        }
        return $this->jsonMessage(200, true, '获取成功!', $row);
    }


    /**
     * 修改
     *
     */
    public function edit($id)
    {

        $row = $this->model->find($id);
        if (empty($row)) {
            return $this->jsonMessage(201, false, '数据不存在', null);
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            try {
                $this->validate && validate($this->validate)->scene('edit')->check($post);
                $result = $row->save($post);
                if ($result) {
                    return $this->jsonMessage(200, true, '保存成功!', null);
                }
                return $this->jsonMessage(201, false, '保存失败', null);
            } catch (ValidateException $e) {
                return $this->jsonMessage(201, false, $e->getError(), null);
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return $this->jsonMessage(201, false, '保存失败', null);
            }
        }
        return $this->jsonMessage(200, true, '获取成功!', $row);
    }




    /**
     * @desc   获取角色列表
     * @author zhangheng
     * @date   2024-10-22
     */
    public function roleList()
    {
        $params      = $this->request->post();
        $list        = $this->model
            ->field('id,name')
            ->order('create_time asc')
            ->select()
            ->toArray();
        return $this->jsonMessage(200, true, '获取成功!', $list);
    }

}
